/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.windfly.don.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import cn.windfly.don.DonConfig;

/**
 * 请求耗时
 * 
 * @author Administrator
 */
@WebFilter(urlPatterns = { "/*" })
public class RequestTakeTimeFilter implements Filter {
	private int d = DonConfig.getInt("don.log.request.longtime", 0);

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
			long s = System.currentTimeMillis();
			chain.doFilter(request, response);
		if (d > 0) {
			long dis = System.currentTimeMillis() - s;
			if (dis > d) {
				HttpServletRequest req = (HttpServletRequest) request;
				System.out.println(("[请求耗时过长],uri:" + req.getRequestURI() + "耗时(毫秒):" + dis + " params:"
						+ request.getParameterMap()));
			}
		}
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String initParameter = filterConfig.getInitParameter("requestTakeTime");
		try {
			if (initParameter != null) {
				d = Integer.parseInt(initParameter);
			}
		} catch (NumberFormatException e) {
			System.err.println("初始化参数错误,必须为数字,requestTakeTime=" + initParameter);
		}
	}
}